package com.elecboarduniversal

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.provider.Settings.Secure
import com.sxintelbox.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException
import java.util.logging.Logger


class RestartService: Service() {

    private var lastNotificationTime: Long = 0
    private val handler = Handler(Looper.getMainLooper())
    private val CHECK_INTERVAL = 2 * 60 * 1000L // 每隔 2分钟 检查一次

    private val CHANNEL_ID = "my_service_channel"
    private val NOTIFICATION_ID = 1
    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()

        // 如果你需要创建一个通知渠道（在Android O及以上版本中必需）
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val channel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel(
                    CHANNEL_ID,
                    "My Service Channel",
                    NotificationManager.IMPORTANCE_HIGH
            ).apply {
                description = "Channel for my foreground service"
            }
        } else {
            TODO("VERSION.SDK_INT < O")
        }
        notificationManager.createNotificationChannel(channel)

        // 注意：不要在这里调用startForeground()，因为它应该在onStartCommand()中调用
        // 以确保在每次服务启动时都能显示通知

        // 设定一个定时任务来检查是否收到了通知
        handler.postDelayed({
            checkIfAppIsResponsive()
        }, CHECK_INTERVAL) // CHECK_INTERVAL 是你定义的检查间隔
    }
    private val client = OkHttpClient()
    private fun checkIfAppIsResponsive() {
        // 检查最后通知时间，如果超过了预设的阈值
        if (System.currentTimeMillis() - lastNotificationTime > 5 * 60 * 1000L) {
            // 这里不能直接重启应用，但可以通过其他方式通知用户或尝试恢复状态
            // 例如，发送一个广播到主应用，让主应用自己处理重启逻辑
            Logger.getLogger("RestartService").warning("checkIfAppIsResponsive: 超过5分钟未收到通知，尝试重启应用");
            sendBroadcast(Intent(this, MainAppReceiver::class.java).apply {
                action = "com.elecboarduniversal.RestartAppService.action.RESTART_APP"
            })

            // 重新设置定时器
            handler.postDelayed({
                checkIfAppIsResponsive()
            }, CHECK_INTERVAL)
        } else {
            Logger.getLogger("RestartService").warning("checkIfAppIsResponsive: 检查");
            // 如果没有超时，则继续检查
            handler.postDelayed({
                checkIfAppIsResponsive()
            }, CHECK_INTERVAL)
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // 处理来自主线程的通知
        if (intent?.action == "com.elecboarduniversal.RestartAppService.action.APP_ALIVE") {
            lastNotificationTime = System.currentTimeMillis()
        }
        else {
            // 显示前台服务通知
            val notification = createForegroundNotification()
            startForeground(NOTIFICATION_ID, notification)
        }
        return START_STICKY
    }

    private fun createForegroundNotification(): Notification {
        val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification.Builder(this, CHANNEL_ID)
                    .setContentTitle("班牌")
                    .setContentText("班牌监控应用")
                    .setSmallIcon(R.mipmap.ic_launcher)
        } else {
            TODO("VERSION.SDK_INT < O")
        } // 使用你的应用图标

        // 如果你需要设置其他通知属性，可以在这里进行
        // ...

        return builder.build()
    }
}